﻿using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Security.Principal;
using System.Web;
using System.Web.Mvc;
using System.Web.Routing;
using System.Web.Security;
using MvcMusicStore.Models;
using LibraryMusicStore;
using Microsoft.Practices.Unity;
using MvcMusicStore.Infrastructure.Untils;

namespace MvcMusicStore.Controllers
{

    [HandleError]
    //public class AccountController : Controller
    //{
        #region old
        //public IFormsAuthenticationService FormsService { get; set; }
        //public IMembershipService MembershipService { get; set; }

        //private void MigrateShoppingCart(string userName)
        //{
        //    /// Associate shopping cart items with logged-in user 
        //    var cart = ShoppingCart.GetCart(this.HttpContext);

        //    cart.MigrateCart(userName);
        //    Session[ShoppingCart.CartSessionKey] = userName;
        //}

        //protected override void Initialize(RequestContext requestContext)
        //{
        //    if (FormsService == null) { FormsService = new FormsAuthenticationService(); }
        //    if (MembershipService == null) { MembershipService = new AccountMembershipService(); }

        //    base.Initialize(requestContext);
        //}

        //// **************************************
        //// URL: /Account/LogOn
        //// **************************************

        //public ActionResult LogOn()
        //{
        //    return View();
        //}

        //[HttpPost]
        //public ActionResult LogOn(LogOnModel model, string returnUrl)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (MembershipService.ValidateUser(model.UserName, model.Password))
        //        {
        //            MigrateShoppingCart(model.UserName);

        //            FormsService.SignIn(model.UserName, model.RememberMe);
        //            if (!String.IsNullOrEmpty(returnUrl))
        //            {
        //                return Redirect(returnUrl);
        //            }
        //            else
        //            {
        //                return RedirectToAction("Index", "Home");
        //            }
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "Tài khoản hoặc mật khẩu không đúng.");
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    return View(model);
        //}

        //// **************************************
        //// URL: /Account/LogOff
        //// **************************************

        //public ActionResult LogOff()
        //{
        //    FormsService.SignOut();

        //    return RedirectToAction("Index", "Home");
        //}

        //// **************************************
        //// URL: /Account/Register
        //// **************************************

        //public ActionResult Register()
        //{
        //    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //    return View();
        //}

        //[HttpPost]
        //public ActionResult Register(RegisterModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        // Attempt to register the user
        //        MembershipCreateStatus createStatus = MembershipService.CreateUser(model.UserName, model.Password, model.Email);

        //        if (createStatus == MembershipCreateStatus.Success)
        //        {
        //            MigrateShoppingCart(model.UserName);

        //            FormsService.SignIn(model.UserName, false /* createPersistentCookie */);
        //            return RedirectToAction("Index", "Home");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", AccountValidation.ErrorCodeToString(createStatus));
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        //// **************************************
        //// URL: /Account/ChangePassword
        //// **************************************

        //[Authorize]
        //public ActionResult ChangePassword()
        //{
        //    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //    return View();
        //}

        //[Authorize]
        //[HttpPost]
        //public ActionResult ChangePassword(ChangePasswordModel model)
        //{
        //    if (ModelState.IsValid)
        //    {
        //        if (MembershipService.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword))
        //        {
        //            return RedirectToAction("ChangePasswordSuccess");
        //        }
        //        else
        //        {
        //            ModelState.AddModelError("", "Mật khẩu hiện tại không hợp lệ hoặc mật khẩu mới không đúng.");
        //        }
        //    }

        //    // If we got this far, something failed, redisplay form
        //    ViewData["PasswordLength"] = MembershipService.MinPasswordLength;
        //    return View(model);
        //}

        //// **************************************
        //// URL: /Account/ChangePasswordSuccess
        //// **************************************

        //public ActionResult ChangePasswordSuccess()
        //{
        //    return View();
        //}

        #endregion
    //}

    public class AccountController : BaseController
    {
        [Dependency]
        public IRepository Repository { get; set; }

        [HttpGet]
        public ActionResult LogOn()
        {
            try
            {
                var model = new LogOnModel
                {
                    ReturnUrl = Request.QueryString["ReturnUrl"]
                };
                return View(model);
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        [HttpPost]
        public ActionResult LogOn(LogOnModel model)
        {
            try
            {
                if (!ModelState.IsValid)
                    return View(model);

                Repository = new Repository();
                var user = Repository.ValidateUser(model.username, model.password.Encrypt());

                if (user != null)
                {
                    return StoreAuthCookieAndRedirect(user.userid, model.ReturnUrl, model.RememberMe);
                }
                ModelState.AddModelError(string.Empty, "Sai tài khoản hoặc mật khẩu");
                return View("LogOn");
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        private ActionResult StoreAuthCookieAndRedirect(int userID, string returnUrl, bool remember)
        {
            FormsAuthentication.SetAuthCookie(userID.ToString(), remember);
            return string.IsNullOrEmpty(returnUrl)
                ? (ActionResult)RedirectToAction("Index", "Home")
                : Redirect(returnUrl.UrlDecode());
        }

        [HttpGet]
        public ActionResult LogOff(string returnUrl)
        {
            try
            {
                FormsAuthentication.SignOut();
                returnUrl = string.IsNullOrEmpty(returnUrl) ? "/" : returnUrl;
                return Redirect(returnUrl.UrlDecode());
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        [HttpGet]
        public ActionResult Setup()
        {
            return View();
        }

        [HttpGet]
        public ActionResult Register()
        {
            ViewData["PasswordLength"] = RegisterModel.MinPasswordLength;

            return View();
        }

        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            try
            {
                if (!ModelState.IsValid || model.password.Length < RegisterModel.MinPasswordLength)
                {
                    ViewData["PasswordLength"] = RegisterModel.MinPasswordLength;
                    ModelState.AddModelError("",
                        "Mật khẩu phải hơn " + RegisterModel.MinPasswordLength + " kí tự");
                    return View(model);
                }

                Repository = new Repository();

                var user = Repository.FindUserByLoginName(model.username);
                if (user != null)
                {
                    ModelState.AddModelError("Login", "Tài khoản đã tồn tại");
                    return View(model);
                }
                var newUser = new User
                {
                    username = model.username,
                    password = model.password.Encrypt(),
                    //Website = model.Website,
                    email = model.email,
                    fullname = model.fullname ?? model.username,
                    address = model.address,
                    city = model.city,
                    country = model.country,
                    phone = model.phone,
                    roleid = 2
                    //IsOwner = false
                };

                Repository.AddUser(newUser);
                Repository.CommitChanges();

                return RedirectToLogin();
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        [Authorize]
        public ActionResult ChangeInfomation(int userid)
        {
            try
            {
                Repository = new Repository();
                ViewData["User"] = Repository.FindUserByID(userid);
                return View();
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangeInfomation(ChangeInfomationModel model)
        {
            try
            {
                Repository = new Repository();

                var user = Repository.FindUserByID(model.userid);

                if (ModelState.IsValid)
                {
                    user.email = model.email;
                    user.fullname = model.fullname ?? user.username;
                    user.city = model.city;
                    user.address = model.address;
                    user.country = model.country;
                    user.phone = model.phone;

                    Repository.CommitChanges();

                    return View("ChangeInfomationSuccess");
                }

                // If we got this far, something failed, redisplay form
                //ViewData["User"] = Repository.FindUserByID(int.Parse(((String[])model.userid)[0]));
                ViewData["User"] = user;
                return View(model);
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }


        [Authorize]
        public ActionResult ChangePassword()
        {
            ViewData["PasswordLength"] = RegisterModel.MinPasswordLength;
            return View();
        }

        [Authorize]
        [HttpPost]
        public ActionResult ChangePassword(ChangePasswordModel model)
        {
            try
            {
                Repository = new Repository();

                var user = Repository.FindUserByID(Convert.ToInt32(User.Identity.Name));

                if (!ModelState.IsValid ||
                    model.NewPassword.Length < RegisterModel.MinPasswordLength ||
                    user.password != model.OldPassword.Encrypt())
                {
                    ViewData["PasswordLength"] = RegisterModel.MinPasswordLength;
                    ModelState.AddModelError("", "Mật khẩu hiện tại không đúng hoặc mật khẩu mới không hợp lệ.");
                    return View(model);
                }

                user.password = model.NewPassword.Encrypt();

                Repository.CommitChanges();

                // If we got this far, something failed, redisplay form

                return View("ChangePasswordSuccess");
            }
            catch (Exception)
            {
                return View("../Shared/Error");
            }
        }
    }
}
